//
//  NotificationEngine.m
//  Growth
//
//  Created by 洪波 陈 on 5/9/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "NotificationEngine.h"

#import "PublicMethodEngine.h"
#import "PublicDatabaseEngine.h"

#import "WebRequest.h"
#import "CJSONSerializer.h"

@implementation NotificationEngine
static NotificationEngine *_shareEngine = nil;
static NSInteger notificationNumber = 0;

static WebConnectionArray *postPushtoken_connection;


+ (NotificationEngine *)sharedNotificationEngine
{
	if (!_shareEngine) {
		_shareEngine = [[NotificationEngine alloc] init];
	}
	
	return _shareEngine;
}


- (void)dealloc
{
    
    if (postPushtoken_connection != nil) {
        postPushtoken_connection.connectionDelegate = nil;
        [postPushtoken_connection release];
        postPushtoken_connection = nil;
    }
    
    [super dealloc];
}

#pragma mark -
#pragma mark Unit Method

- (void)removeNotification
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    notificationNumber = 0;
}

- (void)notifitionWith:(NSString *)infoStr fireDate:(NSDate *)fireDate
{
    
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    
    CLog(@"Notifition add %@", fireDate);
    
    localNotif.fireDate = fireDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    
    localNotif.alertBody = infoStr;
    //localNotif.alertAction = NSLocalizedString(@"View Details", nil);
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    
    localNotif.applicationIconBadgeNumber = ++notificationNumber;
    //localNotif.alertLaunchImage = @"Icon.png";
    
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"null" forKey:@"null"];
    localNotif.userInfo = infoDict;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}

- (float)timeIntervalBetween:(NSDate *)dateOne dateTwo:(NSDate *)dateTwo
{
     NSTimeInterval timeInterval = [dateOne timeIntervalSinceDate:dateTwo];
    
    return timeInterval>0 ?timeInterval :-timeInterval;
}

- (float)timeIntervalWith:(NSInteger)week day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second
{
    static float weekTimeInterval = 604800.0f;
    static float dayTimeInterval = 86400.0f;
    static float hourTimeInterval = 3600.0f;
    static float minuteTimeInterval = 60.0f;
    static float secondTimeInterval = 1.0f;
    
    return weekTimeInterval *week + dayTimeInterval *day +hourTimeInterval *hour +minuteTimeInterval *minute +secondTimeInterval *second;
}

- (float)timeIntervalWith:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second
{
    
    return [self timeIntervalWith:0 day:day hour:hour minute:minute second:second];
}

#pragma mark -
#pragma mark Own Notification
- (void)plansNotification
{
    //读取计划数据库对一段时间内的计划添加Notification
    NSString *sql = @"select name, time_distance, description, available, category from LocalPlan order by category";
    NSArray *sqlArray = [NSArray arrayWithObjects:@"name", @"time_distance", @"description", @"available", @"category", nil];
    NSArray *planArray = [[PublicDatabaseEngine sharedDatabaseEngine] searchWithSQL:sql select:sqlArray];
    
    CLog(@"Plans count: %d", [planArray count]);
    
    if (planArray) {
        PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];
        
        for (NSDictionary *dict in planArray) {
            if (dict) {
                NSString *dateStr = [dict objectForKey:@"time_distance"];
                NSDate *date = [methodEngine NSStringDateToNSDate:dateStr];
                NSDate *dateStandard = [methodEngine NSStringDateToNSDate:@"2012-01-01 00:00:00"];
                
                float timeDelay = [self timeIntervalBetween:date dateTwo:dateStandard];
                
                NSString *notiName = [dict objectForKey:@"name"];
                
                [self notifitionWith:notiName fireDate:[[NSDate date] addTimeInterval:timeDelay]];
            }
        }
    }
    
}


- (void)recordRemindNotification
{
    if (RECORD_ALERT) {
         NSDate *zoneDate = [NSDate date];
        NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
        NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
        NSDate *currentDate=[NSDate dateWithTimeIntervalSinceNow:interval];
       
        CLog(@"Zone date %@", zoneDate);
        CLog(@"Current date %@", currentDate);
        
        PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];
        
        NSString *currentDateStr = [methodEngine NSDateToNSTring:currentDate];
        NSString *timeStr = RECORD_ALERT_TIME;
        currentDateStr =  [currentDateStr substringToIndex:11];
        currentDateStr = [currentDateStr stringByAppendingFormat:[NSString stringWithFormat:@"%@:00",timeStr]];

        CLog(@"AlertDateZero Str %@",currentDateStr);
        
        NSDate *alertDateZero = [methodEngine NSStringDateToNSDate:currentDateStr];
        alertDateZero = [alertDateZero addTimeInterval:-1 *interval];   //转回到标准时间

        CLog(@"AlertDateZero %@",alertDateZero);
        
        for (int i = 0; i <30; i++) {
            
            NSDate *alertDate = [methodEngine dateWithDaysFromDate:i date:alertDateZero];
            
            NSTimeInterval distance = [alertDate timeIntervalSinceDate:zoneDate];
            
            CLog(@"distance %f", distance);
            
            if (distance < 0) {
                continue;
            }
            
            CLog(@"alert date %d %@",i ,alertDate);
            
            [self notifitionWith:@"我又长大了一点，快来记录吧！" fireDate:alertDate];
        }
    }

}


#pragma mark -Post DeviceToken
- (BOOL)postDeviceToken
{
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] valueForKey:DEVICE_TOKEN_KEY];
    
    NSString *keyStr = [NSString stringWithFormat:@"%@%@", userId, deviceToken];
    BOOL isPost = [[[NSUserDefaults standardUserDefaults] valueForKey:keyStr] boolValue];
    if (isPost) {
        CLog(@"device token have post!");
        return  YES;
    }

    
    if (userId != nil && deviceToken != nil) {
        NSArray *keys = [NSArray arrayWithObjects:@"uid", @"osType", @"pushToken", nil];
        NSArray *objects = [NSArray arrayWithObjects:userId, @"ios", deviceToken, nil];
        
        NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
        NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        //   	
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        //	
        NSMutableURLRequest * request = [WebRequest pushtokenModifyRequestWith:_jsonData];
        
        CLog(@"Post pushtoken request %@", request);
        
        if (postPushtoken_connection != nil) {
            postPushtoken_connection.connectionDelegate = nil;
        }
        postPushtoken_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
        
        
        
        return YES;
    }
    else {
        return NO;
    }
    
}

- (void)postDeviceTokenWithAlert
{
    if (![self postDeviceToken]) {
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"prefs:root=NOTIFICATIONS_ID"]]) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"如果您要使用提醒功能，需要您在设置—>通知中开启对“印象宝贝”的授权！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
            [alert release];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"如果您要使用提醒功能，需要您在设置—>通知中开启对“印象宝贝”的授权！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            
            [alert show];
            [alert release];
        }
        
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            
            break;
        }
        case 1:
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=NOTIFICATIONS_ID"]]; 
            break;
        }
        default:
            break;
    }
}

#pragma mark - connection delegate
- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    NSRange range = [url rangeOfString:@"user/pushtoken/modify"];
    
    
    if (range.length > 0) {
        CLog(@"Pushtoken Modify Return  %@",dict);
        NSDictionary *infoDit = [dict objectForKey:@"object"];
        
        NSInteger errorCode = [[infoDit objectForKey:@"errorCode"] intValue];
        
        if (errorCode == 0|| errorCode == 14) {
             CLog(@"Pushtoken Modify Return  errorcode %d",errorCode);
            NSString *userId = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
            NSString *deviceToken = [[NSUserDefaults standardUserDefaults] valueForKey:DEVICE_TOKEN_KEY];
            NSString *keyStr = [NSString stringWithFormat:@"%@%@", userId, deviceToken];
            
            [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:keyStr];
        }
    }
}

- (void)connectionArrayError:(NSError *)error
{

}

#pragma mark -

@end
